﻿using Business;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Common;

namespace WinUI.Frm_Program
{
    public partial class Frm_ViewProgram : Form
    {
        public Frm_ViewProgram()
        {
            InitializeComponent();
        }

        #region Khai báo biến thành viên
        private SafeBindingSource _bdSourceProgram = null;
        public Business.Program _SE;
        private int _currRowHandle = -1;
        private string _messageSystemError = String.Empty;
        private List<ComboItem> listEmployeeForCombo;
        private List<ComboItem> listCustomerForCombo;
        private List<ComboItem> listBrandForCombo;
        private MyProgram _currentProgram = null;
        private ComboItem _currentCustomerForEdit = null;
        #endregion

        private void Frm_ViewProgram_Load(object sender, EventArgs e)
        {
            DevExpress.Data.CurrencyDataController.DisableThreadingProblemsDetection = true;
            _SE = new Business.Program();
            _bdSourceProgram = new SafeBindingSource();
            listEmployeeForCombo = new List<ComboItem>();
            listCustomerForCombo = new List<ComboItem>();
            listBrandForCombo = new List<ComboItem>();
            _currentCustomerForEdit = new ComboItem();

            Employee.GetEmployeeByJobForCombo(ref listEmployeeForCombo, "CS");
            Customer.GetAllForCombo(ref listCustomerForCombo);
            Brand.GetAllForCombo(ref listBrandForCombo);

            rI_ccb_CS.DataSource = listEmployeeForCombo;
            rI_ccb_CS.DisplayMember = "Text";
            rI_ccb_CS.ValueMember = "Value";

            rI_Search_Customer.DataSource = listCustomerForCombo;
            rI_Search_Customer.DisplayMember = "Text";
            rI_Search_Customer.ValueMember = "ID";

            rI_Search_Brand.DataSource = listBrandForCombo;
            rI_Search_Brand.DisplayMember = "Text";
            rI_Search_Brand.ValueMember = "ID";

            _currentProgram = new MyProgram();
            InitBackgroundWorker();
        }

        private void __bdSourceProgram_PositionChanged(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        private void Frm_ViewProgram_Shown(object sender, EventArgs e)
        {
            if (!_backgroundWorker.IsBusy)
            {
                _backgroundWorker.RunWorkerAsync(LOAD_DATA_TASK);
            }
            else
                BackgroundWorkerIsBusy();
        }

        private void BindingDataToGrvGameResult()
        {
            List<Business.MyProgram> listProgram = new List<Business.MyProgram>();
            Common.ERROR_CODE.ERROR_CODE_ITEMS_SELECT errCode = Business.Program.GetProgramByUserID(ref _messageSystemError, ref listProgram, Global._UserInfo);
            _bdSourceProgram.DataSource = listProgram;
            gridControl.Invoke(new Action<DevExpress.XtraGrid.GridControl>((grc) => grc.BeginUpdate()), gridControl);
            gridControl.Invoke(new Action<DevExpress.XtraGrid.GridControl>((grc) => grc.DataSource = _bdSourceProgram), gridControl);
            _taskResult = Global.GetTaskResult((int)errCode, errCode, _messageSystemError);
        }

        public void Search()
        {
            if (!_backgroundWorker.IsBusy)
            {
                _backgroundWorker.RunWorkerAsync(LOAD_DATA_TASK);
            }
        }

        #region Xử lý bất đồng bộ
        private string _currTask = String.Empty;
        private string _taskResult = String.Empty;
        private const string LOAD_DATA_TASK = "LOAD_DATA";
        private const string UPDATE_TASK = "UPDATE";
        private CustomBackgroundWorker _backgroundWorker = null;

        /// <summary>
        /// Disable Form
        /// </summary>
        private void FreezeUI()
        {
            mainTableLayoutPanel.Invoke(new Action<TableLayoutPanel>((tbLayOut) => tbLayOut.Enabled = false), mainTableLayoutPanel);
        }

        /// <summary>
        /// Enable Form
        /// </summary>
        private void UnFreezeUI()
        {
            mainTableLayoutPanel.Invoke(new Action<TableLayoutPanel>((tbLayOut) => tbLayOut.Enabled = true), mainTableLayoutPanel);
        }

        private void InitBackgroundWorker()
        {
            _backgroundWorker = new CustomBackgroundWorker();
            _backgroundWorker.WorkerSupportsCancellation = true;
            _backgroundWorker.WorkerReportsProgress = true;
            _backgroundWorker.DoWork += _backgroundWorker_DoWork;
            _backgroundWorker.RunWorkerCompleted += _backgroundWorker_RunWorkerCompleted;
        }

        void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            _currTask = String.Empty;
            splashScreenManager.ShowWaitForm();
            string task = e.Argument.ToString();
            switch (task)
            {
                case LOAD_DATA_TASK:
                    _currTask = LOAD_DATA_TASK;
                    FreezeUI();
                    BindingDataToGrvGameResult();
                    break;
                case UPDATE_TASK:
                    _currTask = UPDATE_TASK;
                    _currentProgram = (Business.MyProgram)_bdSourceProgram[_currRowHandle];
                    Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE errCode = Business.Program.Update(ref _messageSystemError, ref _currentProgram, Global._UserInfo);
                    _taskResult = Global.GetTaskResult((int)errCode, errCode, _messageSystemError);
                    break;
            }
        }

        void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            splashScreenManager.CloseWaitForm();
            mainTableLayoutPanel.Invoke(new Action<TableLayoutPanel>((tbLayOut) => tbLayOut.Enabled = true), mainTableLayoutPanel);
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message, Common.MESSAGE_TITLE.ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (!String.IsNullOrEmpty(_taskResult))
            {
                string[] arr = _taskResult.Split('|');
                if (arr[0] != "1") //trường hợp lỗi
                    MessageBox.Show(arr[1], Common.MESSAGE_TITLE.ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (_currTask == LOAD_DATA_TASK)
            {
                UnFreezeUI();
                gridControl.Invoke(new Action<DevExpress.XtraGrid.GridControl>((grc) => grc.EndUpdate()), gridControl);
            }

            gridView.BestFitColumns();
        }

        private void BackgroundWorkerIsBusy()
        {
            MessageBox.Show(Common.MESSAGE_STRING.IN_PROGRESS, Common.MESSAGE_TITLE.INFO, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        #endregion

        private void gridView_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            _currRowHandle = e.RowHandle;
            if (!_backgroundWorker.IsBusy)
            {
                _backgroundWorker.RunWorkerAsync(UPDATE_TASK);
            }

            if (!String.IsNullOrEmpty(_taskResult))
            {
                string[] arr = _taskResult.Split('|');
                if (arr[0] != "1") //trường hợp lỗi
                    e.Valid = false;
            }
        }

        private void gridView_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            _currRowHandle = e.RowHandle;
            _currentProgram = (Business.MyProgram)_bdSourceProgram[_currRowHandle];
            if (e.Column == col_customer)
            {
                //var customerID = gridView.GetFocusedRowCellValue("CustomerID").ToString();
                //var listBrand = listBrandForCombo.Where(p => p.Value.Equals(customerID)).ToList();
                //_currentProgram.BrandID = int.Parse(listBrand.FirstOrDefault().ID.ToString());
            }
            else if (e.Column == col_CS)
            {
                if (_currentProgram.ListEmployeeCode == null) _currentProgram.ListEmployeeCode = new List<string>();
                foreach (var item in _currentProgram.Field_CS.Split(','))
                {
                    _currentProgram.ListEmployeeCode.Add(item);
                }
            }
        }

        private void gridView_CustomRowCellEditForEditing(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e)
        {
            if (e.Column == col_Product)
            {
                List<ComboItem> listBrand = new List<ComboItem>();
                var customerID = gridView.GetFocusedRowCellValue("CustomerID").ToString();
                listBrand = listBrandForCombo.Where(p => p.Value.Equals(customerID)).ToList();

                // 
                // Column
                // 
                var col = new DevExpress.XtraGrid.Columns.GridColumn();
                col.Caption = "Brand";
                col.FieldName = "Text";
                col.Visible = true;
                col.VisibleIndex = 0;

                // 
                // gridView
                // 
                var grid = new DevExpress.XtraGrid.Views.Grid.GridView();
                grid.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] {
                col});
                grid.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
                grid.OptionsSelection.EnableAppearanceFocusedCell = false;
                grid.OptionsView.ShowGroupPanel = false;

                DevExpress.XtraEditors.Repository.RepositoryItemSearchLookUpEdit ri = new DevExpress.XtraEditors.Repository.RepositoryItemSearchLookUpEdit();
                ri.View = grid;
                ri.DataSource = listBrand;
                ri.ValueMember = "ID";
                ri.DisplayMember = "Text";

                e.RepositoryItem = ri;
            }
        }

        private void gridView_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            _currRowHandle = e.RowHandle;
            _currentProgram = (Business.MyProgram)_bdSourceProgram[_currRowHandle];
            if (e.Column == col_customer)
            {
                var customerID = e.Value.ToString();
                var listBrand = listBrandForCombo.Where(p => p.Value.Equals(customerID)).ToList();
                _currentProgram.BrandID = int.Parse(listBrand.FirstOrDefault().ID.ToString());
            }
        }

        private void bt_Search_Click(object sender, EventArgs e)
        {

        }
    }
}
